#include "commtraff.h"
#include "commtraff_hilog.h"
#include "commtraff_socket_client.h"
#include <string.h>


static CommTraffQueryCb g_cQueryCb = {NULL, NULL};
static int32_t g_queryCount = 0;

void OnClientRecv(char *buffer, int length);

static ClientRecvCb g_clientCb = {
    .OnRecv = OnClientRecv
};

void OnClientRecv(char *buffer, int length)
{
    if (buffer == NULL || length < sizeof(CommTraffCommand)) {
        LOGE("OnClientRecv: Invalid buffer or length");
        return;
    }
    LOGI("OnClientRecv: Received data length=%d", length);
    CommTraffCommand *cmd = (CommTraffCommand *)buffer;
    if (cmd->cmdType == COMMTRAFF_CMD_QUERY_RESULT) {
        CommTraffResult *result = &cmd->data.result;
        // 边界检查：验证记录数量的合理性
        if (result->recordNums < 0) {
            LOGE("OnClientRecv: Invalid recordNums=%d (negative value)", result->recordNums);
            return;
        }
        // 边界检查：验证buffer大小是否足够容纳所有记录数据
        size_t expectedSize = sizeof(CommTraffCommand) + (size_t)result->recordNums * sizeof(CommTraff);
        if (length < expectedSize) {
            LOGE("OnClientRecv: Buffer too small - received %d bytes, expected %zu bytes for %d records",
                    length, expectedSize, result->recordNums);
            return;
        }
        g_queryCount += result->recordNums;
        CommTraff *records = result->recordNums > 0 ? (CommTraff *)(buffer + sizeof(CommTraffCommand)) : NULL;
        LOGI("OnClientRecv: Received query result, recordNums=%d, totalCount=%d lastRecordIndex=%lld",
                result->recordNums, g_queryCount, result->lastRecordIndex);
        if (g_cQueryCb.OnQuery != NULL && result->recordNums > 0) {
            g_cQueryCb.OnQuery(records, result->recordNums);
        }

        // server端每次最多返回ONCE_RECORD_NUMS条数据，超过ONCE_RECORD_NUMS条数据则继续查询
        if (result->recordNums < ONCE_RECORD_NUMS && g_cQueryCb.OnComplete != NULL) {
            g_cQueryCb.OnComplete(COMMTRAFF_SUCCESS, g_queryCount);
        } else {
            CommTraffCommand command;
            memset(&command, 0, sizeof(CommTraffCommand));
            command.cmdType = COMMTRAFF_CMD_QUERY_DATABASE;
            command.cPort = GetClientPort();
            command.data.queryRule.traffType = result->traffType;
            command.data.queryRule.startTime = result->startTime;
            command.data.queryRule.endTime = result->endTime;
            command.data.queryRule.startRecordIndex = result->lastRecordIndex;
            SendDataToServer((uint8_t *)&command, sizeof(CommTraffCommand));
        }
    } else {
        LOGE("OnClientRecv: Unknown command type %d", cmd->cmdType);
    }
}


int32_t CommtraffInit()
{
    if (ClientInit(&g_clientCb) != 0) {
        LOGE("SocketServerInit failed");
        return COMMTRAFF_FAIL;
    }
    return COMMTRAFF_SUCCESS;
}

int32_t CommtraffDeinit()
{
    LOGI("commtraff client deinit");
    return COMMTRAFF_SUCCESS;
}

int32_t InsertCommTraff(CommTraff *record)
{
    if (record == NULL) {
        LOGE("InsertCommTraff Invalid parameter");
        return COMMTRAFF_INVALID_PARAM;
    }
    
    // 使用指令消息方式发送插入请求
    CommTraffCommand command;
    memset(&command, 0, sizeof(CommTraffCommand));
    command.cmdType = COMMTRAFF_CMD_INSERT_DATA;
    command.cPort = GetClientPort();
    memcpy(&command.data.insertData, record, sizeof(CommTraff));

    if (SendDataToServer((uint8_t *)&command, sizeof(CommTraffCommand)) != COMMTRAFF_SUCCESS) {
       return COMMTRAFF_FAIL;
    }
    return COMMTRAFF_SUCCESS;
}

int32_t QueryCommTraffNums(CommTraffQueryRule *queryRule)
{
    LOGE("QueryCommTraffNums no implementation");
    return COMMTRAFF_FAIL;
}

/**
 * 查询流量数据记录
 * @param queryRule 查询条件
 * @param cb 回调函数结构体
 * @return 查询结果，成功返回 COMMTRAFF_SUCCESS，失败返回 COMMTRAFF_FAIL
 */
int32_t QueryCommTraff(CommTraffQueryRule *queryRule, CommTraffQueryCb *cb)
{
    // 参数有效性检查
    if (queryRule == NULL) {
        LOGE("QueryCommTraff: queryRule parameter is NULL");
        return COMMTRAFF_INVALID_PARAM;
    }
    
    if (cb == NULL) {
        LOGE("QueryCommTraff: callback parameter is NULL");
        return COMMTRAFF_INVALID_PARAM;
    }
    
    // 检查流量类型有效性
    if (queryRule->traffType < LINK_LAYER_DATA || queryRule->traffType > HISYSEVENT_DATA) {
        LOGE("QueryCommTraff: invalid traffic type %d (must be %d-%d)", 
             queryRule->traffType, LINK_LAYER_DATA, HISYSEVENT_DATA);
        return COMMTRAFF_INVALID_PARAM;
    }
    
    // 检查时间范围有效性 - 开始时间必须小于等于结束时间
    if (queryRule->startTime > queryRule->endTime) {
        LOGE("QueryCommTraff: invalid time range - start time (%ld) must be <= end time (%ld)", 
             queryRule->startTime, queryRule->endTime);
        return COMMTRAFF_INVALID_PARAM;
    }
    
    // 检查时间是否为负值
    if (queryRule->startTime < 0) {
        LOGE("QueryCommTraff: invalid start time %ld (must be >= 0)", queryRule->startTime);
        return COMMTRAFF_INVALID_PARAM;
    }
    
    if (queryRule->endTime < 0) {
        LOGE("QueryCommTraff: invalid end time %ld (must be >= 0)", queryRule->endTime);
        return COMMTRAFF_INVALID_PARAM;
    }
    
    LOGI("QueryCommTraff: querying traffic type %d from %ld to %ld", queryRule->traffType, queryRule->startTime, queryRule->endTime);
    
    // 使用指令消息方式发送查询请求
    CommTraffCommand command;
    memset(&command, 0, sizeof(CommTraffCommand));

    command.cmdType = COMMTRAFF_CMD_QUERY_DATABASE;
    command.cPort = GetClientPort();
    command.data.queryRule.traffType = queryRule->traffType;
    command.data.queryRule.startTime = queryRule->startTime;
    command.data.queryRule.endTime = queryRule->endTime;
    command.data.queryRule.startRecordIndex = 0;

    g_cQueryCb = *cb;
    g_queryCount = 0;

    return SendDataToServer((uint8_t *)&command, sizeof(CommTraffCommand));
}
